<template>
  <div>
    <!--    <el-button type="primary" @click="delrouterall()">click</el-button>-->
    <!--    <el-button @click="test()">test</el-button>-->
    <router-link :to="{path: '/jc/dev/ywxxwh/15'}"> wewaaa</router-link>
    <div style="font: 20px bold ; margin: 0px 10px;">{{ dev.name }}</div>
    <hr style="margin: 20px 0 0 0">

    <div style="margin: 10px 0">
      <el-button size="small" type="primary" style="margin: 0 10px" @click="$router.back()">返回</el-button>
      <el-button size="small" type="primary" style="margin: 0 10px" @click="showNewForm">新增<i
          class="el-icon-circle-plus"></i></el-button>
      <el-popconfirm
          confirm-button-text='确定'
          cancel-button-text='取消'
          icon="el-icon-info"
          icon-color="red"
          title="确定删除吗？"
          @confirm="handleDelBatch"
      >
        <el-button size="small" type="danger" slot="reference" style="margin: 10px 10px">
          批量删除
          <i class="el-icon-remove-outline"></i>
        </el-button>
      </el-popconfirm>
      <div style="float: right">
        <el-input style="width: 200px; margin: 0 10px 0 10px" placeholder="请输入业务名"
                  suffix-icon="el-icon-search"
                  v-model="name"/>

        <el-button type="primary" @click="search">搜索</el-button>
      </div>
    </div>


    <el-dialog title="新增" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="formRules" ref="form">
        <el-form-item label="业务名" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="寄存器地址" :label-width="formLabelWidth" prop="location">
          <el-input v-model="form.location" autocomplete="off"></el-input>
        </el-form-item>
        <!--        <el-form-item label="业务类型" :label-width="formLabelWidth">-->
        <!--          <el-select v-model="form.specialtypeid" placeholder="请选择业务类型">-->
        <!--            <el-option-->
        <!--                v-for="item in specialtypeArr"-->
        <!--                :label="item.name"-->
        <!--                :value="item.id">-->
        <!--            </el-option>-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->

        <el-form-item label="寄存器类型" :label-width="formLabelWidth" prop="regtype">
          <el-select v-model="form.regtype" placeholder="请选择寄存器类型" @change="handleNewSelChange">
            <el-option label="线圈" :value="0"></el-option>
            <el-option label="离散输入" :value="1"></el-option>
            <el-option label="输入寄存器" :value="3"></el-option>
            <el-option label="保持寄存器" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据类型" :label-width="formLabelWidth" prop="regdatatp">
          <el-select v-model="form.regdatatp" placeholder="请选择数据类型">
            <el-option
                v-for="item in form.datatypes"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="编辑" :visible.sync="editFormVisible">
      <el-form :model="editform" :rules="editFormRules" ref="editform">
        <el-form-item label="业务名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="editform.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="寄存器地址" :label-width="formLabelWidth" prop="location">
          <el-input v-model="editform.location" autocomplete="off"></el-input>
        </el-form-item>
        <!--        <el-form-item label="业务类型" :label-width="formLabelWidth">-->
        <!--          <el-select v-model="editform.specialtypeid" placeholder="请选择业务类型">-->
        <!--            <el-option-->
        <!--                v-for="item in specialtypeArr"-->
        <!--                :label="item.name"-->
        <!--                :value="item.id">-->
        <!--            </el-option>-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <!--        4个分区有只读区和读写区，并且命名为 : 0x、1x、3x、4x-->

        <!--        0x：形象的叫做线圈（coil status）,意味着可读可写（获取状态，设置状态），用功能码01，05，15操作这部分的寄存器-->
        <!--        1x：离散输入（inputs status），很明显这是一块只读区。只能用功能码02 操作-->
        <!--        3x：输入寄存器（input registers），也是一块只读区，只能用功能码04操作-->
        <!--        4x：保持寄存器（holding registers），这是一块可读可写的数据区，用功能码03、06、16 操作这部分的寄存器-->
        <!--        ————————————————-->

        <!--        版权声明：本文为博主原创文章，遵循 CC 4.0 BY-SA 版权协议，转载请附上原文出处链接和本声明。-->

        <!--        原文链接：https://blog.csdn.net/syusyorin/article/details/134310453-->
        <el-form-item label="寄存器类型" :label-width="formLabelWidth" prop="regtype">
          <el-select v-model="editform.regtype" placeholder="请选择寄存器类型" @change="handleEditSelChange">
            <el-option label="线圈" :value="0"></el-option>
            <el-option label="离散输入" :value="1"></el-option>
            <el-option label="输入寄存器" :value="3"></el-option>
            <el-option label="保持寄存器" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据类型" :label-width="formLabelWidth" prop="regdatatp">
          <el-select v-model="editform.regdatatp" placeholder="请选择数据类型">
            <el-option
                v-for="item in editform.datatypes"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleEidt">确 定</el-button>
      </div>
    </el-dialog>

    <el-table ref="table" @selection-change="handleSelectionChange" :data="tableData"
              style="margin: 10px; width: 1600px" border stripe>
      <el-table-column width="50" type="selection">
      </el-table-column>
      <el-table-column type="index" label="序号" width="60">
      </el-table-column>

      <el-table-column prop="id" label="ID" width="60" v-if="false">
      </el-table-column>
      <el-table-column prop="name" label="业务名" width="200">
      </el-table-column>

      <!--      <el-table-column prop="specialtypeObj.name" label="业务类型" width="200">-->
      <!--      </el-table-column>-->
      <el-table-column label="寄存器类型" width="200">
        <template slot-scope="scope">
          <span v-if="scope.row.regtype === 0">线圈</span>
          <span v-if="scope.row.regtype === 1">离散输入</span>
          <span v-if="scope.row.regtype === 3">输入寄存器</span>
          <span v-if="scope.row.regtype === 4">保持寄存器</span>
        </template>
      </el-table-column>
      <el-table-column label="数据类型" width="200">
        <template slot-scope="scope">
          <span v-if="scope.row.regdatatp === 2">16位无符号整数</span>
          <span v-if="scope.row.regdatatp === 3">16位整数</span>
          <span v-if="scope.row.regdatatp === 4">32位无符号整数</span>
          <span v-if="scope.row.regdatatp === 5">32位整数</span>
          <span v-if="scope.row.regdatatp === 8">32位float</span>
          <span v-if="scope.row.regdatatp === 1">bool</span>
        </template>
      </el-table-column>
      <el-table-column prop="location" label="寄存器地址" width="200">
      </el-table-column>
      <el-table-column prop="devObj.name" label="所属设备" width="200">
      </el-table-column>

      <el-table-column prop="#" label="操作">
        <template slot-scope="scope">

          <el-button size="small" type="primary" @click="showEditForm(scope.row)">编辑<i
              class="el-icon-edit"></i></el-button>
          <!--              <el-button type="danger" slot="reference">删除<i class="el-icon-remove-outline"></i></el-button>-->

          <el-popconfirm
              style="margin: 0 10px"
              confirm-button-text='确定'
              cancel-button-text='取消'
              icon="el-icon-info"
              icon-color="red"
              title="确定删除吗？"
              @confirm="handleDel(scope.row.id)"
          >
            <el-button size="small" type="danger" slot="reference">删除<i class="el-icon-remove-outline"></i>
            </el-button>
          </el-popconfirm>
          <!--          <el-button size="small" type="success" slot="reference">业务类型配置 <i class="el-icon-set-up"></i>-->
          <!--          </el-button>-->

        </template>
      </el-table-column>
    </el-table>


    <div class="block" style="padding: 5px">
      <el-pagination

          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100,500,1000]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

  </div>

</template>
<script>
import service from "@/utils/request";
import ElementUI from "element-ui";

import VueRouter from 'vue-router'
import HomeView from "@/views/HomeView.vue";


export default {

  watch: {
    // 监听路由是否变化
    '$route'(to, from) {
      // if(to.query.id != from.query.id){
      //   this.id = to.query.id; // 把最新id赋值给定义在data中的id
      //   this.init(); // 重新调用加载数据方法
      // }
    }
  },


  created() {
    service.get('/dev/getById', {
      params: {
        id: this.$route.query.id
      }
    }).then(
        response => {
          if (response.data.code == 20000) {
            this.dev = response.data.data
            return service.get('/specialtype/getListBydevtypeid', {
              params: {
                devtypeid: this.dev.devtype
              }
            })
          }
        }
    ).then(
        response => {
          if (response.data.code == 20000) {
            this.specialtypeArr = response.data.data
            this.load();
          }
        }
    )

  },
  activated() {
    console.log(this.$route.query.id)
    service.get('/dev/getById', {
      params: {
        id: this.$route.query.id
      }
    }).then(
        response => {
          if (response.data.code == 20000) {
            this.dev = response.data.data
            return service.get('/specialtype/getListBydevtypeid', {
              params: {
                devtypeid: this.dev.devtype
              }
            })
          }
        }
    ).then(
        response => {
          if (response.data.code == 20000) {
            this.specialtypeArr = response.data.data
            this.devid = this.$route.query.id
            this.name = ''
            this.load();
          }
        }
    )

  },
  data() {
    return {
      devid: this.$route.query.id,
      dev: {},
      specialtypeid: null,
      name: null,
      specialtypeArr: [],
      // datatypes:[],


      tableData: [],
      selectedRows: [], // 用来存储选中行的数据
      pageSize: 10,
      total: 100,
      currentPage: 1,
      dialogFormVisible: false,
      editFormVisible: false,
      form: {
        name: '',
        location: null,
        devid: this.$route.query.id,
        regtype: null,
        regdatatp: null,
        datatypes: []
      },
      formRules: {
        name: [
          {required: true, message: '请输入业务名', trigger: 'blur'},
        ],
        location: [
          {required: true, message: '请输入寄存器地址', trigger: 'blur'},
        ],
        regtype: [
          {required: true, message: '请选择寄存器类型', trigger: 'blur'},
        ],
        regdatatp: [
          {required: true, message: '请选择数据类型', trigger: 'blur'},
        ],
      },

      editform: {
        id: null,
        name: '',
        location: null,
        // specialtypeid: null,
        devid: this.$route.query.id,
        regtype: null,
        regdatatp: null,
        datatypes: []
      },
      editFormRules: {
        name: [
          {required: true, message: '请输入业务名', trigger: 'blur'},
        ],
        location: [
          {required: true, message: '请输入寄存器地址', trigger: 'blur'},
        ],
        regtype: [
          {required: true, message: '请选择寄存器类型', trigger: 'blur'},
        ],
        regdatatp: [
          {required: true, message: '请选择数据类型', trigger: 'blur'},
        ],
      },

      formLabelWidth: '120px'
    }
  },
  methods: {
    test() {

    },
    load() {
      service.get('/reg/getpageWithObj', {
        params: {
          pagesize: this.pageSize,
          pagenum: this.currentPage,
          name: this.name,
          devid: this.devid,
          specialtypeid: this.specialtypeid
        }
      }).then(response => {
            if (response.data.code == 20000) {
              this.tableData = response.data.data.records;
              this.total = response.data.data.total;
              this.currentPage = response.data.data.current;
              this.pageSize = response.data.data.size;
            }
          },
          error => {
            ElementUI.Message({
              message: error.message,
              type: 'error'
            })
          }
      );
    },
    handleNewSelChange(val) {
      console.log(this.form.datatypes)
      if (val == 0 || val == 1) {//线圈 离散输入
        this.form.datatypes = [{id: 1, name: '布尔'}]

      } else if (val == 3 || val == 4) {//保持寄存器  输入寄存器
        this.form.datatypes = [
          {id: 2, name: '16位无符号整数'},
          {id: 3, name: '16位整数'},
          {id: 4, name: '32位无符号整数'},
          {id: 5, name: '32位整数'},
          {id: 8, name: '32位float'}]

      }
      this.form.regdatatp = null
    },
    handleEditSelChange(val) {
      console.log(this.editform.datatypes)
      if (val == 0 || val == 1) {//线圈
        this.editform.datatypes = [{id: 1, name: '布尔'}]
      } else if (val == 3 || val == 4) {//保持寄存器
        this.editform.datatypes = [
          {id: 2, name: '16位无符号整数'},
          {id: 3, name: '16位整数'},
          {id: 4, name: '32位无符号整数'},
          {id: 5, name: '32位整数'},
          {id: 8, name: '32位float'}]
      }
      this.editform.regdatatp = null
    },


    dwchange(dw) {
      console.log(this.editform.dwid)
    },

    handleSelectionChange(selection) {
      // console.log(selection)
      // this.selectedRows = selection.map(row => row._row);
      this.selectedRows = selection
      // console.log(this.selectedRows)
    },

    showNewForm() {
      // this.form = {}
      this.form.regdatatp = null
      this.form.location = null
      this.form.name = null
      this.form.regtype = null
      this.form.datatypes = []
      this.dialogFormVisible = true
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.load()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.load()
    },

    handleSave() {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return;
        }
        let saveform = {}
        saveform.name = this.form.name
        saveform.location = this.form.location
        // saveform.specialtypeid = this.form.specialtypeid
        saveform.devid = this.devid
        saveform.regtype = this.form.regtype
        saveform.regdatatp = this.form.regdatatp

        service.post('/reg/save', saveform).then(response => {
          if (response.data.code == 20000) {
            this.$message.success('success!');
            this.dialogFormVisible = false
            this.load()
          } else {
            this.$message.error("error")
            this.dialogFormVisible = false
          }
        })

      })

    },
    showConfirmForm(row) {

    },

    showEditForm(row) {
      // this.editform = {}
      this.editform.id = row.id
      this.editform.name = row.name
      this.editform.location = row.location
      // this.editform.specialtypeid = row.specialtypeid
      this.editform.devid = row.devid
      this.editform.regtype = row.regtype
      this.editform.regdatatp = row.regdatatp
      if (this.editform.regtype == 1 || this.editform.regtype == 0) {
        this.editform.datatypes = [{id: 1, name: '布尔'}]
      } else if (this.editform.regtype == 3 || this.editform.regtype == 4) {
        this.editform.datatypes = [
          {id: 2, name: '16位无符号整数'},
          {id: 3, name: '16位整数'},
          {id: 4, name: '32位无符号整数'},
          {id: 5, name: '32位整数'},
          {id: 8, name: '32位float'}]
      }
      this.editFormVisible = true

    },

    handleEidt() {
      this.$refs["editform"].validate((valid) => {
        if (!valid) {
          return;
        }
        let editformTmp = {}
        editformTmp.id = this.editform.id
        editformTmp.name = this.editform.name
        editformTmp.location = this.editform.location
        // editformTmp.specialtypeid = this.editform.specialtypeid
        editformTmp.regdatatp = this.editform.regdatatp
        editformTmp.regtype = this.editform.regtype
        service.post('/reg/edit', editformTmp).then(response => {
          if (response.data.code == 20000) {
            this.$message.success('success!');
            this.editFormVisible = false
            this.load()
          } else {
            this.$message.error("error")
            this.editdialogFormVisible = false
          }
        })
      })
    },
    handleDel(id) {
      service.delete('/reg?id=' + id).then(response => {
        if (response.data.code == 20000) {
          this.$message.success('删除成功!');
          this.load()
        } else {
          this.$message.error("error")
        }

      })
    },
    search() {
      this.load()
    },
    handleDelBatch() {
      service.post('/reg/delbatch', this.selectedRows).then(response => {
        if (response.data.code == 20000) {
          this.$message.success('删除成功!');
          this.load()
        } else {
          this.$message.error("error")
        }
      })
    },
    uploadFile(param) {
      //param中的file才是真正的文件体，用于传入axios上传方法的参数

      const header = {"content-type": "multipart/form-data"} //请求头设置，没必要加，axios看到formdata类型，会自动加上，
      let formData = new FormData();
      formData.append("file", param.file);
      service.post('/dev/import', formData).then(res => {
        if (res.data.code == 20000) {
          this.$message.success('导入成功!');
          this.load()
        } else {
          this.$alert(res.data.message, '导入错误！', {
            confirmButtonText: '确定',
          })
          this.load()
        }
      }, error => {
        this.$alert(error.message, '错误！', {
          confirmButtonText: '确定',
        })
      })
    },

  }
}
</script>

<style scoped>

</style>
